
#include <time.h>

#include "tp_typedef.h"
#include "tp_source_timer.h"
#include "tp_memory.h"

typedef struct _PrivInfo 
{
	int interval;
	time_t timestamp;

	TpOnTimer on_timer;
	void* user_data;
}PrivInfo;

static int tp_source_timer_get(TpSource* thiz)
{
	return -1;
}

static int tp_source_timer_check(TpSource* thiz)
{
	DECL_PRIV(thiz, priv);

	int time_elapsed= time(NULL) - priv->timestamp;
	int time_left = priv->interval - time_elapsed;

	return time_left > 0 ? time_left : 0;
}

static TpRet tp_source_timer_dispatch(TpSource* thiz)
{
	DECL_PRIV(thiz, priv);
	if (NULL == priv)
	{
		return TP_RET_FAIL;
	}

	priv->timestamp = time(NULL);

	return priv->on_timer(priv->user_data);
}

static void tp_source_timer_destroy(TpSource* thiz)
{
	tp_free(thiz);

	return;
}

TpSource* tp_source_timer_create(int interval, TpOnTimer on_timer, void* user_data)
{
	TpSource* thiz = (TpSource*)tp_alloc(sizeof(TpSource) + sizeof(PrivInfo));
	if (NULL != thiz)
	{
		DECL_PRIV(thiz, priv);

		priv->interval = interval;
		priv->timestamp = time(NULL);
		priv->on_timer = on_timer;
		priv->user_data = user_data;
	}

	return thiz;
}